/***********************************************
 This file is part of redia-bapps-main-ios.
 
 Copyright (c) 2015 Redia A/S
 
 Redia-bapps-main-ios is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 Redia-bapps-main-ios is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with redia-bapps-main-ios.  If not, see <http://www.gnu.org/licenses/>.
 
 *********************************************** */

//
//  BAOpeningHoursCell.m
//  redia-bapps-ios
//
//  Created by Nikolaj Tørring on 05/11/13.
//  Copyright (c) 2013 redia. All rights reserved.
//

#import "BAOpeningHoursCell.h"
#import "BAOpeningHoursInterval.h"
#import "BALibrarySettings.h"

@interface BAOpeningHoursCell()

@property (weak, nonatomic) IBOutlet UIImageView *backgroundImageView;
@property (weak, nonatomic) IBOutlet UIImageView *upArrowImageView;
@property (weak, nonatomic) IBOutlet UIImageView *downArrowImageView;

@property (weak, nonatomic) IBOutlet UILabel *dayLabel;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;

@property (weak, nonatomic) IBOutlet UIView *expandedContainer;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *labelContainerTralingSpace;

@end
@implementation BAOpeningHoursCell



- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
    }
    return self;
}

-(void)awakeFromNib{
    _selectedHeight = 49;
    BA_LABEL_SET_FONT_REGULAR(self.dayLabel);
    BA_LABEL_SET_FONT_REGULAR(self.timeLabel);
    [self.upArrowImageView setImage:[[BALibrarySettings instance] getCachedImageNamed:@"arrow-up-smalldisclose"
                                                                    multiplyWithColor:[[BALibrarySettings instance] getCustomerColorNormal]]];
    [self.downArrowImageView setImage:[[BALibrarySettings instance] getCachedImageNamed:@"arrow-down-smalldisclose"
                                                                    multiplyWithColor:[[BALibrarySettings instance] getCustomerColorNormal]]];
}

-(void)setDay:(BAOpeningHoursDay *)day{
    _day = day;
    
    if (day==nil || [day.intervals count]==0) {
        [self.timeLabel setText:@"Lukket"];
        [self.upArrowImageView removeFromSuperview];
        [self.downArrowImageView removeFromSuperview];
        self.labelContainerTralingSpace.constant = 25;
        return;
    }
    
    BAOpeningHoursInterval* firstInterval = [day.intervals count]>0 ? [day.intervals objectAtIndex:0] : nil;
    
    BAOpeningHoursInterval* totalInterval = [BAOpeningHoursInterval new];
    [totalInterval setOpen:firstInterval.open];
    [totalInterval setClose:firstInterval.close];
    
    for (BAOpeningHoursInterval* interval in day.intervals) {
        
        if (interval.open < totalInterval.open) {
            [totalInterval setOpen:interval.open];
        }
        
        if (interval.close > totalInterval.close) {
            [totalInterval setClose:interval.close];
        }
    }

    [self setInterval:totalInterval forLabel:self.timeLabel];
    
    
    if (day.intervals.count == 1 && firstInterval.note.length == 0) {
        [self.upArrowImageView removeFromSuperview];
        [self.downArrowImageView removeFromSuperview];
        _isShowingDiscloseButton=NO;
    }
    else{
        _isShowingDiscloseButton=YES;
        [self setupIntervals:day];
    }
    
    
}

-(void)keepSpaceForDiscloseButton:(BOOL)keepSpace
{
    if (keepSpace) {
        self.labelContainerTralingSpace.constant = 55;
    } else {
        self.labelContainerTralingSpace.constant = 25;
    }
}

-(void)setInterval:(BAOpeningHoursInterval*)interval forLabel:(UILabel*)label{
    [label setText:[NSString stringWithFormat:@"%02d:%02d - %02d:%02d", interval.open / 3600, (interval.open / 60) % 60, interval.close / 3600, (interval.close / 60) % 60]];
}

-(void)setDayName:(NSString *)dayName{
    _dayName = dayName;
    [self.dayLabel setText:dayName];
}

-(void)setIndex:(NSInteger)index{
    _index = index;
    UIImage* bgImage;
    if (index%2 == 0) {
        bgImage = [[UIImage imageNamed:@"opening-cell-bg-light"] resizableImageWithCapInsets:UIEdgeInsetsMake(4, 0, 4, 0)];
    }else{
        bgImage = [[UIImage imageNamed:@"opening-cell-bg-dark"] resizableImageWithCapInsets:UIEdgeInsetsMake(4, 0, 4, 0)];
    }
    [self.backgroundImageView setImage:bgImage];
}

-(void)setupIntervals:(BAOpeningHoursDay *)day{
    
    NSArray* sortedIntervals = [day.intervals sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NSInteger first = [(BAOpeningHoursInterval*)obj1 open];
        NSInteger second = [(BAOpeningHoursInterval*)obj2 open];
        return first > second;
    }];
    
    UIView* previousView;
    
    for (BAOpeningHoursInterval* interval in sortedIntervals) {
        UIView* containerView = [UIView new];
        UILabel* noteLabel = [UILabel new];
        UILabel* timeLabel = [UILabel new];
        [containerView addSubview:noteLabel];
        [containerView addSubview:timeLabel];
        [self.expandedContainer addSubview:containerView];
        
        [noteLabel setBackgroundColor:[UIColor clearColor]];
        [timeLabel setBackgroundColor:[UIColor clearColor]];
        
        [containerView setBackgroundColor:[UIColor clearColor]];
        [noteLabel setFont:BA_FONT_LIGHT(self.dayLabel.font.pointSize)];
        [timeLabel setFont:self.timeLabel.font];
        [noteLabel setTextColor:self.dayLabel.textColor];
        [timeLabel setTextColor:self.timeLabel.textColor];
        [noteLabel setNumberOfLines:2];

        [noteLabel setText:interval.note];
        [self setInterval:interval forLabel:timeLabel];
        
        containerView.translatesAutoresizingMaskIntoConstraints = NO;
        noteLabel.translatesAutoresizingMaskIntoConstraints = NO;
        timeLabel.translatesAutoresizingMaskIntoConstraints = NO;
        
        [containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[noteLabel]-100-|" options:0 metrics: 0 views:NSDictionaryOfVariableBindings(noteLabel)]];
        [containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[noteLabel]|" options:0 metrics: 0 views:NSDictionaryOfVariableBindings(noteLabel)]];
        [containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[timeLabel]|" options:0 metrics: 0 views:NSDictionaryOfVariableBindings(timeLabel)]];
        [containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[timeLabel]|" options:0 metrics: 0 views:NSDictionaryOfVariableBindings(timeLabel)]];
        
        [self.expandedContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-25-[containerView]-55-|" options:0 metrics: 0 views:NSDictionaryOfVariableBindings(containerView)]];
        
        if (previousView == nil) {
            [self.expandedContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-2-[containerView]" options:0 metrics: 0 views:NSDictionaryOfVariableBindings(containerView)]];
        } else{
            [self.expandedContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[previousView]-3-[containerView]" options:0 metrics: 0 views:NSDictionaryOfVariableBindings(containerView, previousView)]];
        }
        previousView = containerView;
    }
    if (previousView != nil) {
        [self.expandedContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[previousView]-15-|" options:0 metrics: 0 views:NSDictionaryOfVariableBindings(previousView)]];
    }
    [self layoutIfNeeded];
    NSLog(@"%@", NSStringFromCGRect(self.expandedContainer.frame));
    
    _selectedHeight = self.expandedContainer.frame.origin.y + self.expandedContainer.frame.size.height;
}


-(void)setSelected:(BOOL)selected{
    [self setSelected:selected animated:NO];
}

-(void)setSelected:(BOOL)selected animated:(BOOL)animated{
    if (selected == super.selected) {
        return;
    }
    if (selected) {
        [self.upArrowImageView setAlpha:1];
        [self.downArrowImageView setAlpha:0];
    }else{
        [self.upArrowImageView setAlpha:0];
        [self.downArrowImageView setAlpha:1];
    }
    
    [super setSelected:selected animated:animated];
}
@end
